<template>
	<div class="main" :style="{ zoom: zoom }">
		<div class="top_bg" :class="{'is-expanded': isInfoVisible}" @mouseleave="mouseleaveChange">
			<div class="TopMin320" >
				<div class="top_logo left">今生永恒网</div>
				<div class="top_left left" @mouseenter="mouseenterChange" >
					<div class="jngname">{{ muDetail.name }}网上墓园 <b class="caret"></b></div>
				</div>
				<div class="centerdiv">
					<marquee onmouseover="this.stop()" onmouseout="this.start()" scrollamount="2" scrolldelay="4" width="100%" height="38" align="center">{{ muDetail.sacrificial_word }}</marquee>
				</div>
				<div class="top_right">
					<div id="ulogin" v-if="!isLogin">
						<button style="background-color: #FFA500;" @click="goToLogin">用户登录</button>
					</div>
					<div id="ulogin" v-else style="width: 100%;height: 100%;display: flex;gap: 0 10px;align-items: center;justify-content: flex-start;color: #fff;">
						<span class="header-user-nickname">{{ userInfo?.nickname || '用户' }}</span>
						<el-button class="header-button" @click="handleManageCenter" type="info">管理</el-button>
					</div>
				</div>
			</div>
			<div class="jnginfo"  v-show="isInfoVisibleText">
				<p>
					<strong>永远怀念家驹</strong>
					<br>纪念馆编号：<span>{{ muDetail.id }}</span>
					<br>公共账户永恒币：<span id="jngtb">38</span>
					<!-- <el-button type="primary" @click="joinFamily" style="margin-left: 10px;">申请加入家族</el-button> -->
				</p>
			</div>
		</div>
		<div class="jngbox">
			<div class="mubj" ref="memorialArea">
				<div class="mubei"></div>
			</div>
			<div class="mubeic" :style="{ backgroundImage: `url(${muDetail.template_info?.old_cover})`}" v-if="muDetail.clear_time == 0 || muDetail.repair_time == null || daysPassedSince(muDetail.repair_time * 1000) > 120">
				<!-- <img :src="muDetail.template_info.old_cover" alt="" style="width: auto;height: auto;"> -->
			</div>
			<div class="beiwen" style="width: 140px; height: 260px; left: 886px; top: 323px;">
				<div class="beiphoto" style="width: 100%;display: flex;align-items: flex-start;justify-content: center;">
					<img :src="muDetail.avatar" border="0" style="width: 60px;height: 60px;">
				</div>
				<!-- <div class="beitext" style="">
					<span class="nametext name1">郑然</span>
					<span class="zhimu">之<br>墓</span>
				</div> -->
				<div class="tombstone-gallery">
					<TombstoneInfo
						:name="muDetail.name"
						epitaph="之墓"
					/>
				</div>
			</div>

			<!-- <div class="box box-4" id="jpboxmain">
				<div class="t-shade"></div>
				<div class="t-content"></div>

			</div> -->
			<!-- 祭品区域 -->
			<div class="offerings-area" v-if="offerings.length > 0">
				<!-- 祭品台 -->
				<!-- 可拖动的祭品 -->
				<div v-for="(offering, index) in offerings" :key="offering.id" class="offering-item"
					:class="{ 'dragging': isDragging && draggedOffering?.id === offering.id }"
					:style="getOfferingPosition(offering)" @mousedown="startDrag($event, offering)"
					@touchstart="startDrag($event, offering, true)" ref="draggableRefs">
					<!-- :ref="(el) => setDraggableRef(el as HTMLElement | null, index)" -->
					<img :src="offering.cover" />

					<span>请将祭品拖动<br>到摇摆放的位置</span>
				</div>
			</div>
		</div>
		<!-- 左侧导航 -->
		<div class="side-nav">
			<div v-for="(item, index) in navItems" :key="index" class="nav-item" @click="handleNavClick(item)">
				{{ item.name }}
			</div>
		</div>
		

		<!-- 底部操作栏 -->
		<div class="bottom-actions">
			<div class="action-button" @click="showOfferingDialog(item.name, item.id)" v-for="item in giftCateList" :key="item.id" :style="{flex: item.name.length > 2 ? '2' : '1'}">
				<!-- <i class="icon-flower"></i> -->
				{{ item.name }}
			</div>
		</div>
		<!-- 祭品选择弹窗 -->
		<!-- <el-dialog v-model="offeringDialogVisible" :title="dialogTitle" width="50%" class="offering-dialog">
			<div class="offering-list">
				<div v-for="item in currentOfferingItems" :key="item.id" class="offering-option"
					@click="selectOffering(item)">
					<img src="@/assets/images/flower1.png">
					<div class="offering-info">
						<div class="name">{{ item.name }}</div>
						<div class="price">{{ item.price }}永恒币</div>
					</div>
				</div>
			</div>
		</el-dialog> -->
		<gift-popup ref="giftPopupRef" v-if="showEdit" @success="selectOffering" @close="showEdit = false" :tabIndex="tabIndex" :muDetail="muDetail"></gift-popup>
		<gift-confirm ref="giftConfirmRef" v-if="showConfirm" @success="confirmOffering" @close="closeGiftOffering" :muDetail="muDetail"></gift-confirm>

		<div class="placed-item-display" v-for="item in imageList" :key="item.id" :style="getItemStyle(item)" @mouseenter="mouseenterItem(item)"  @mouseleave="mouseleaveItem">
		 	<div style="width: 100%;height: 100%;position: relative;">
				<img alt="" :src="item.cover" style="width: auto;height: auto;" class="placed-item"/>
				<transition name="info-overlay-fade">
					<div v-if="hoverItemId === item.id" class="hover-info-overlay-simple">
						<p class="hover-info-text-simple">祭品名称：{{ item.name || '无描述' }}</p>
						<p class="hover-info-text-simple">祭奠人：{{ item.nick_name || '网友' }}</p>
						<p class="hover-info-time-simple">祭奠时间：{{ currentCountdownString || '无时间' }}</p>
					</div>
				</transition>
			</div>
			<!-- 可以显示寄语等 -->
		</div>
		<div class="graveyard_audio" :class="{ 'playing': isPlaying }">
			<img src="@/assets/images/music_none.png" alt="" @click="playAudio" v-if="isPlaying">
			<img src="@/assets/images/music_block.png" alt="" @click="pauseAudio" v-else>
			<audio ref="audioElement" :src="muDetail.mp3_url" :autoplay="true" :loop="true" style="width: 0px;height: 0px;" controls @play="audioPlay" @pause="audioPause">
			</audio>
		</div>
		<div class="graveyard_fullScreen" @click="toggleFullScreen">
			<img src="@/assets/images/fullScreen.png" alt="" v-if="!isFullScreen">
			<img src="@/assets/images/offFullScreen.png" alt="" v-else>
		</div>
		<div class="graveyard_QRcode" @click="showQrCode">
			<img src="@/assets/images/qrcodeIcon.png" alt="">
		</div>
		<!-- <el-dialog v-model="isShowQrCode" :title="muDetail.name + '网上墓园二维码'" width="auto">
            <div class="qrcode-view">
                <QrcodeVue 
                    :value="qrValue" 
                    class="qrcode-element"
                    id="qrcode"
                    ref="qrcodeRef"
                    render-as="canvas"
                    :size="200"
                />
                <el-button @click="downloadQrcode">下载</el-button>
            </div>
        </el-dialog> -->
        <QrCodePage 
            v-model="isShowQrCode" 
            :qr-value="qrValue" 
            :title="muDetail.name + '网上墓园二维码'"
        />
        <!-- 登录弹窗组件 -->
        <LoginDialog 
            v-model="showLoginDialog" 
            @login-success="handleLoginSuccess"
            @register-success="handleRegisterSuccess"
        />
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, nextTick, toRaw, shallowRef } from 'vue'
import type { Ref, CSSProperties } from 'vue'
import { apiMuGiftCate, apiMuGiftList, apiMuGiftAdd, apiMemorialGiftList } from '@/api/gift'
import { user_join, index_share_img } from '@/api/family'
import { apiMuDetail } from '@/api/graveyard'
import GiftPopup from './giftPopup.vue'
import GiftConfirm from './giftConfirm.vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import LoginDialog from '@/components/LoginDialog/index.vue'
import feedback from '@/utils/feedback'
import TombstoneInfo from './info.vue'; // 确保路径正确
import audio_img from '@/assets/images/audio_img.jpg'
import { daysPassedSince } from '@/utils/util'
import useUserStore from '@/stores/modules/user'
import { getToken } from '@/utils/auth'
import QrcodeVue from 'qrcode.vue'; // 导入 qrcode.vue 组件
import QrCodePage from '@/components/qrCodePage.vue';

const route = useRoute() // 路由
const router = useRouter() // 路由
const userStore = useUserStore() // 用户
const giftPopupRef = shallowRef<InstanceType<typeof GiftPopup>>() // 祭品编辑弹窗
const giftConfirmRef = shallowRef<InstanceType<typeof GiftConfirm>>() // 祭品确认弹窗
const showEdit = ref(false) // 祭品编辑弹窗
const showConfirm = ref(false) // 祭品确认弹窗
const isInfoVisible = ref(false); // 是否显示信息
const isInfoVisibleText = ref(false); // 是否显示信息

// 登录弹窗相关数据
const showLoginDialog = ref(false)


interface OfferingItem {
	id: number
	name: string
	image: string
	price: number
	type: string
	position?: {
		x: number
		y: number
	}
}

interface NavItem {
	name: string
	key: string,
	path?: string
}

// 导航项
const navItems = reactive<NavItem[]>([
	{ name: '生平', key: 'life', path: 'memorialDetail?pageType=1' },
	{ name: '文章', key: 'articles', path: '/article?pid=1' },
	{ name: '相册', key: 'photos', path: '/memorialDetail?pageType=1' },
	{ name: '留言', key: 'messages', path: '/memorialDetail?pageType=1' },
	{ name: '献歌', key: 'songs', path: '/memorialDetail?pageType=1' },
	{ name: '视频', key: 'videos', path: '/memorialDetail?pageType=1' },
	{ name: '转告', key: 'forward' }
])

// 纪念馆信息
const memorialInfo = reactive({
	name: '张某某',
	id: '102309570'
})

// 已放置的祭品
const offerings = ref<OfferingItem[]>([])
const draggableRefs = ref<(HTMLElement | null)[]>([])

// 祭品选择弹窗
const offeringDialogVisible = ref(false)
const currentOfferingType = ref('')

// 弹窗标题
const dialogTitle = computed(() => {
	const titles: Record<string, string> = {
		flower: '献花',
		incense: '上香',
		candle: '点烛',
		offering: '祭品',
		decoration: '装饰',
		clean: '扫墓'
	}
	return titles[currentOfferingType.value] || '选择祭品'
})

// 所有可选祭品列表
const allOfferingItems = reactive<OfferingItem[]>([])

// 当前类型的祭品列表
const currentOfferingItems = computed(() => {
	return allOfferingItems.filter((item: OfferingItem) => item.type === currentOfferingType.value)
})



// 数据
const giftCateList = ref([])
const giftList = ref([])
const getpiMuGiftList = async () => {
	if(tabIndex.value){
		const res = await apiMuGiftList({cid: tabIndex.value, mu_id: route.query.id})
		console.log(res)
		giftList.value = res
	}else{

		let data = giftCateList.value.find(item => item.name == '献花') as any
		const res = await apiMuGiftList({cid: data.id, mu_id: route.query.id})
		console.log(res)
		giftList.value = res
	}
}


const getApiMuGiftCate = async () => {
	const res = await apiMuGiftCate({mu_id: route.query.id})
	console.log(res)
	giftCateList.value = res.sort((a: any, b: any) => a.id - b.id)
	// giftCateList.value = res
}

// 获取详情
const muDetail = ref({})
const getMuDetail = async () => {
	const res = await apiMuDetail({id: route.query.id})
	console.log(res)
	let arr = []
	if(res.mp3_url != '' && res.mp3_url){
		arr = res.mp3_url.split('.')
		res.mp3_url_type = 'audio/' + arr[arr.length - 1]
	}
	qrValue.value = 'https://cqjsyh.com/H5/pages/detail/index?id=' + route.query.id
	
	muDetail.value = res
}
// 获取纪念馆祭品

const imageList = ref([])
const getApiMemorialGiftList = async () => {
	const res = await apiMemorialGiftList({mu_id: route.query.id})
	console.log(res)
	imageList.value = res.list.filter((item: any) => item.name !== '扫墓' && item.name !== '修缮')
}

const getItemStyle = (item: any) => {

	let arr = item.position?item.position.split(',') : [80, 70]

	if(arr[0] > 100 || arr[1] > 100) {
		arr = [80, 70]
	}

	return {
		left: `${arr[0]}%`,
		top: `${arr[1]}%`,
		zIndex: '199'
	}
}


// ===== 添加的部分 开始 =====
const hoverItemId = ref<number | string | null>(null); // 跟踪当前悬停的 item ID
// 存储当前活动倒计时的显示字符串
const currentCountdownString = ref<string>('');
// 存储当前活动的 setInterval 的 ID
const activeIntervalId = ref<ReturnType<typeof setInterval> | null>(null);
// 简单的日期格式化函数 (如果 item.timestamp 不存在或无效，返回提示)
// 计算并格式化倒计时字符串的函数 (保持不变)
const calculateCountdownString = (endTime: Date | string | number | undefined): string => {
  if (!endTime) {
    return '无结束时间';
  }
  let endMillis: number;
  try {
    endMillis = new Date(Number(endTime) * 1000).getTime();
    if (isNaN(endMillis)) throw new Error('Invalid Date');
  } catch (e) {
    return '无效时间';
  }
  const nowMillis = Date.now();
  const diff = endMillis - nowMillis;
  if (diff <= 0) {
    return '已结束';
  }
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((diff % (1000 * 60)) / 1000);
  return `${days}天 ${hours}时 ${minutes}分 ${seconds}秒`;
};

// ===== 添加的部分 结束 =====

const mouseenterItem = (item: any) => {
	console.log('鼠标悬停=========================',item)
	hoverItemId.value = item.id; // 设置悬停的 item ID

	// 2. 清除可能存在的上一个计时器 (以防万一 mouseleave 未触发)
	if (activeIntervalId.value) {
		clearInterval(activeIntervalId.value);
		activeIntervalId.value = null;
	}

	// 3. 立即计算并显示一次当前的倒计时
	const initialCountdown = calculateCountdownString(item.end_time);
	currentCountdownString.value = initialCountdown;

	// 4. 如果尚未结束，启动新的计时器
	if (initialCountdown !== '已结束' && initialCountdown !== '无效时间' && initialCountdown !== '无结束时间') {
		activeIntervalId.value = setInterval(() => {
		// 在计时器内部，我们仍然需要引用当前 hover 的 item 来获取最新的 endTime
		// 但更简单的方法是直接使用闭包中的 item.endTime
		const updatedCountdown = calculateCountdownString(item.end_time);
		currentCountdownString.value = updatedCountdown;

		// 如果倒计时结束了，清除这个计时器
		if (updatedCountdown === '已结束') {
			if (activeIntervalId.value) {
			clearInterval(activeIntervalId.value);
			activeIntervalId.value = null;
			}
		}
		// 注意：如果 hoverItemId 变化（鼠标移到另一个项），这个旧的 interval 理论上还在运行
		// 直到 mouseleave 清除它，或者这里的逻辑检测到已结束。
		// handleMouseLeave 中的清除更为关键。
		}, 1000);
	}
};

const mouseleaveItem = () => {
	hoverItemId.value = null; // 清除悬停的 item ID	
	if (activeIntervalId.value) {
		clearInterval(activeIntervalId.value);
		activeIntervalId.value = null;
	}
};






















// 墓碑区域引用
const memorialArea = ref<HTMLElement | null>(null)

// 祭品拖动相关数据
const draggedOffering = ref<OfferingItem | null>(null)
const isDragging = ref(false)
const startX = ref(0)
const startY = ref(0)

// 设置拖拽引用
const setDraggableRef = (el: HTMLElement | null, index: number) => {
	if (el) {
		draggableRefs.value[index] = el
		el.draggable = true
		el.style.cursor = 'move'

		const offering = offerings.value[index]
		el.addEventListener('mousedown', (e: MouseEvent) => {
			startDrag(e, offering, true)
		})
	}
}

// 处理导航点击
const handleNavClick = (item: NavItem) => {
	// 处理导航项点击...
	console.log(item)

	if(item.key == 'videos'){
		// 跳转到视频页
		router.push({
			path: '/memorialDetail',
			query: {
				mu_id: muDetail.value.id,
				type: 'videos'
			}
		})
	} else if(item.key == 'articles'){
		// 跳转到文章页
		router.push({
			path: '/memorialDetail',
			query: {
				mu_id: muDetail.value.id,
				type: 'articles'
			}
		})
	} else if(item.key == 'photos'){
		// 跳转到相册页
		router.push({
			path: '/memorialDetail',
			query: {
				mu_id: muDetail.value.id,
				type: 'photos'
			}
		})
	} else if(item.key == 'life'){
		// 跳转到生活页
		router.push({
			path: '/memorialDetail',
			query: {
				mu_id: muDetail.value.id,
				type: 'life'
			}
		})
	} else if(item.key == 'messages'){
		// 跳转到留言页
		router.push({
			path: '/memorialDetail',
			query: {
				mu_id: muDetail.value.id,
				type: 'messages'
			}
		})
	}

	if(item.key == 'songs'){
		// 跳转到留言页
		router.push({
			path: '/libation',
			query: {
				mu_id: muDetail.value.id,
				title: '献歌'
			}
		})
	}
}
const tabIndex = ref(0)
// 显示祭品选择弹窗
const showOfferingDialog = async (type: string, id: number) => {
	
	
	currentOfferingType.value = type
	tabIndex.value = id
	// offeringDialogVisible.value = true
	showEdit.value = true
	console.log(type)
	await getpiMuGiftList()
	await nextTick()
	giftPopupRef.value?.setFormData({
		// mu_id: props.memorialId,
		giftCateList: giftCateList.value,
		giftList: giftList.value,
		tabIndex: tabIndex.value,
		activeTabName: currentOfferingType.value
	})
	giftPopupRef.value?.open('add')
}
const selectItem = ref<any>(null)
// 选择祭品
const selectOffering = (item: any) => {
	// 检查用户是否已登录
	const token = getToken()
	if (!token) {
		// 未登录，显示登录弹窗
		showEdit.value = false
		showLoginDialog.value = true
		return
	}
	console.log(toRaw(item), item)
	selectItem.value = item
	// 添加新的祭品到默认位置
	if(offerings.value.length > 0){
		offerings.value = []
	}
	offerings.value.push({
		...item,
		position: {
			x: 50,
			y: 50
		}
	})
	console.log(toRaw(offerings.value), offerings.value)
	offeringDialogVisible.value = false
	showEdit.value = false
}
// confirmOffering
const confirmOffering = async (item: any) => {
	console.log('confirmOffering================================================',toRaw(item), item)
	await apiMuGiftAdd({
		mu_id: route.query.id,
		gift_id: item.id,
		position: `${item.position.x},${item.position.y}`
	}).then(async res=>{
		console.log(res)
		await feedback.msgSuccess('添加成功')
	}).catch(async err=>{
		console.log(err)
		await feedback.msgError(err.msg)
	})
	
	showConfirm.value = false
	offerings.value = []
	getMuDetail()
	getApiMemorialGiftList()

}
const closeGiftOffering = async () => {
	showConfirm.value = false
	offerings.value = []
}
const elementWidth = ref<number>(0)
const elementHeight = ref<number>(0)
// 开始拖动
const startDrag = (event: MouseEvent | TouchEvent, offering: OfferingItem, isTouch: any) => {
	console.log('startDrag', event)
	// 阻止触摸事件的默认行为，但允许鼠标事件正常进行
	if (isTouch) {
		console.log('触摸事件')
		event.preventDefault()
	}
	const element = draggableRefs.value // 获取元素引用
	if (!element) return // 确保元素存在
	elementWidth.value = element[0] && element[0].offsetWidth ? element[0].offsetWidth : 0 // 获取元素的实际渲染宽度
	elementHeight.value = element[0] && element[0].offsetHeight ? element[0].offsetHeight : 0 // 获取元素的实际渲染高度


	draggedOffering.value = offering
	isDragging.value = true

	// 记录起始位置
	if ('clientX' in event) {
		startX.value = event.clientX - (Number(elementWidth.value) / 2)
		startY.value = event.clientY - (Number(elementHeight.value) / 2)
	} else if (event.touches && event.touches[0]) {
		startX.value = event.touches[0].clientX - (Number(elementWidth.value) / 2)
		startY.value = event.touches[0].clientY - (Number(elementHeight.value) / 2)
	}

	// 添加移动和结束事件监听器
	document.addEventListener('mousemove', handleDragMove)
	document.addEventListener('touchmove', handleDragMove, { passive: false })
	document.addEventListener('mouseup', endDrag)
	document.addEventListener('touchend', endDrag)
}

// 移动处理
const handleDragMove = (event: MouseEvent | TouchEvent) => {
	if (!isDragging.value || !draggedOffering.value || !memorialArea.value) return

	// 只为触摸事件阻止默认行为
	if ('touches' in event) {
		event.preventDefault()
	}
	const element = draggableRefs.value // 获取元素引用
	if (!element) return // 确保元素存在
	
	elementWidth.value = element[0] && element[0].offsetWidth ? element[0].offsetWidth : 0 // 获取元素的实际渲染宽度
	elementHeight.value = element[0] && element[0].offsetHeight ? element[0].offsetHeight : 0 // 获取元素的实际渲染高度
	console.log('element', toRaw(element), element)
	console.log('element', elementWidth.value, elementHeight.value)
	let clientX, clientY
	if ('clientX' in event) {
		clientX = event.clientX - (Number(elementWidth.value) / 2)
		clientY = event.clientY - (Number(elementHeight.value) / 2)
	} else if (event.touches && event.touches[0]) {
		clientX = event.touches[0].clientX - (Number(elementWidth.value) / 2)
		clientY = event.touches[0].clientY - (Number(elementHeight.value) / 2)
	} else {
		return // 无法确定位置，退出
	}

	const rect = memorialArea.value.getBoundingClientRect()
	const x = ((clientX - rect.left) / rect.width) * 100
	const y = ((clientY - rect.top) / rect.height) * 100

	// 确保位置在有效范围内
	if (draggedOffering.value.position) {
		draggedOffering.value.position = {
			x: Math.max(0, Math.min(100, x)),
			y: Math.max(0, Math.min(100, y))
		}
	}

	console.log('===================================================',toRaw(draggedOffering.value), draggedOffering.value)
	selectItem.value = draggedOffering.value
}

// 结束拖动
const endDrag = async () => {
	if (isDragging.value && draggedOffering.value) {
		console.log('结束拖动', toRaw(draggedOffering.value))
		// 处理结束拖动，保存位置
		// updateOfferingPosition(draggedOffering.value)
	}

	// 重置状态并移除事件监听器
	isDragging.value = false
	draggedOffering.value = null
	document.removeEventListener('mousemove', handleDragMove)
	document.removeEventListener('touchmove', handleDragMove)
	document.removeEventListener('mouseup', endDrag)
	document.removeEventListener('touchend', endDrag)

	showConfirm.value = true
	await nextTick()
	giftConfirmRef.value?.setFormData({
		// mu_id: props.memorialId,
		// giftCateList: giftCateList.value,
		// giftList: giftList.value
		selectItem: offerings.value[0]
	})
}

// 获取祭品位置样式
const getOfferingPosition = (offering: OfferingItem) => {
	if (!offering.position) return {}

	// 当正在拖动当前祭品时，提高z-index
	return {
		position: 'absolute',
		left: `${offering.position.x}%`,
		top: `${offering.position.y}%`,
		zIndex: isDragging.value && draggedOffering.value?.id === offering.id ? '10' : '1',
		// 移除可能在此处的transition，拖动时要禁用过渡效果
	}
}

// 更新祭品位置到后端
const updateOfferingPosition = async (offering: OfferingItem) => {
	try {
		await fetch('/api/offerings/position', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({
				offeringId: offering.id,
				position: offering.position
			})
		})
	} catch (error) {
		console.error('更新位置失败:', error)
	}
}
const zoom = ref(1)
const userInfo = ref<any>(null)
const isLogin = ref<boolean>(false)
const handleManageCenter = () => {
	router.push('/memorialManage')
}
onMounted(async () => {
	console.log(navigator.userAgent)
	console.log(window)
	const userAgent = navigator.userAgent
	const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)
	if (isMobile) {
		zoom.value = 0.5
	}
	zoom.value = (window.innerWidth - 15) / 1920
	fun()

	userInfo.value = userStore.userInfo?userStore.userInfo:null
	isLogin.value = getToken()?true:false

	await getApiMuGiftCate()
	await getApiMemorialGiftList()
	await getMuDetail()
})

const scrollbarWidth = ref(0)
const fun = () => {
	// 创建一个临时div元素
	const outer = document.createElement('div');
	outer.style.visibility = 'hidden';
	outer.style.width = '100px'; // 或者任何固定宽度，确保有滚动条出现
	outer.style.height = '100px'; // 同上，确保有滚动条出现
	outer.style.overflow = 'scroll'; // 此元素必须有滚动条
	document.body.appendChild(outer);
	scrollbarWidth.value = outer.offsetWidth - outer.clientWidth; // 计算差值即为滚动条宽度
	document.body.removeChild(outer); // 清理临时元素
	console.log('scrollbarWidth==================================', scrollbarWidth.value, outer.offsetWidth, outer.clientWidth)
}



// 音频 设置
const audioElement = ref<HTMLAudioElement | null>(null)
const isPlaying = ref<boolean>(false)
const audioPlay = () => {
	audioElement.value?.play()
	isPlaying.value = true
}

const audioPause = () => {
	audioElement.value?.pause()
	isPlaying.value = false
}

const playAudio = () => {
	if (isPlaying.value) {
		audioPause()
	}
}
const pauseAudio = () => {
	if (!isPlaying.value) {
		audioPlay()
	}
}


const isFullScreen = ref(false)
const toggleFullScreen = () => {
	isFullScreen.value = !isFullScreen.value
	if (isFullScreen.value) {
		document.documentElement.requestFullscreen()
		zoom.value = 1
	} else {
		document.exitFullscreen()
		console.log(navigator.userAgent)
	console.log(window)
	const userAgent = navigator.userAgent
	const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)
	if (isMobile) {
		zoom.value = 0.5
	}
	zoom.value = (window.innerWidth - 15) / 1920
	}
}

// 显示二维码
const qrValueUrl = ref(`https://cqjsyh.com/H5/pages/detail/index?id=${route.query.id}`)
const qrValue = ref('')
const isShowQrCode = ref(false)
const qrCodeInfo = ref<any>(null)
const showQrCode = async () => {

	// 获取二维码图片URL
    const res = await index_share_img({ url: qrValueUrl.value })
    qrValue.value = res.url
    isShowQrCode.value = true
}





// 头部信息动画
const mouseenterChange = () => {
	isInfoVisible.value = true
	isInfoVisibleText.value = true
}
// 头部信息动画
const mouseleaveChange = () => {
	isInfoVisible.value = false
}

// 去登录
const goToLogin = () => {
	// 跳转到登录页面
	router.push('/login')
}
// 去个人主页
const goToUser = () => {
	// 跳转到登录页面
	router.push('/memorialManage')
}


// 登录成功处理函数
const handleLoginSuccess = async () => {
	await feedback.msgSuccess('登录成功！')
	showLoginDialog.value = false
	// 可以在这里更新用户状态
	// userStore.setUserInfo(userInfo)
	isLogin.value = true
	userInfo.value = userStore.userInfo?userStore.userInfo:null
}

// 注册成功处理函数
const handleRegisterSuccess = async () => {
	await feedback.msgSuccess('注册成功！')
	showLoginDialog.value = false
	// 可以在这里更新用户状态
	// userStore.setUserInfo(userInfo)
	isLogin.value = true
	userInfo.value = userStore.userInfo?userStore.userInfo:null
}

// 申请加入家族
const joinFamily = () => {
	user_join({family_id: route.query.id}).then((res: any) => {
		if(res.code == 0){
			console.log(res.msg)
		}else{
			ElMessage.error(res.msg)
		}
	})
}
</script>

<style scoped>
.main {
	width: 1920px;
	height: 1080px;
	margin: 0 auto;
	position: relative;
	font-size: 1.2rem;
}

.jngbox {
	width: 1920px;
	height: 1080px;
	position: relative;
	overflow: hidden;
}

.mubj {
	background-image: url(../../assets/images/bj2.png);
	width: 1920px;
	height: 100%;
	min-height: 600px;
	top: 0;
	left: 0;
	z-index: 1;
	position: absolute;
	background-position: top center;
	background-size: 1920px auto;
	background-repeat: no-repeat;
}

.mubei {
	width: 1920px;
	height: 1080px;
	top: 0;
	left: 0;
	z-index: 2;
	background-position: bottom center;
	background-size: 1920px auto;
	background-repeat: no-repeat;
	background-image: url(../../assets/images/mudi1.png);
}
.mubeic {
	width: 1920px;
    height: 1080px;
    bottom: 0;
    left: 0;
    z-index: 3;
    position: absolute;
    background-position: bottom center;
    background-repeat: no-repeat;
}
.beiwen {
	z-index: 5;
	position: absolute;
	overflow: hidden;
	background-position: bottom center;
	background-repeat: no-repeat;
}

.side-nav {
      position: fixed;
      /* _position: absolute; */
      font-size: 1rem;
      width: 70px;
      top: 200px;
      left: 0;
      z-index: 1004;
      background-color: rgba(0, 0, 0, 0.3);
      padding: 10px 10px;
      -moz-border-radius: 5px;
      -webkit-border-radius: 5px;
      border-radius: 5px;
  }
  
  .nav-item {
    color: white;
    padding: 5px 0;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
	background-color: #242424;
	border: #8a8a8a 1px solid;
	margin-bottom: 10px;
	border-radius: 5px;
	display: flex;
	align-items: center;
	justify-content: center;
  }
  
  .nav-item:hover {
    background: rgba(0, 0, 0, 0.5);
    /* transform: translateX(5px); */
  }

  /* 底部操作栏 */
  .bottom-actions {
      position: fixed;
      width: 94%;
      min-width: 420px;
      max-width: 700px;
      padding: 8px 12px;
      left: 0;
      right: 0;
      margin: 0 auto;
      background: #000;
      bottom: 30px;
      z-index: 99999;
      background-color: rgba(0, 0, 0, 0.2);
      -moz-border-radius: 10px;
      -webkit-border-radius: 10px;
      border-radius: 10px;
      display: flex;
      justify-content: space-between;
  }
  
  .action-button {
  	flex: 1;
    color: #fff;
	font-size: 1.4rem;
	text-decoration: none;
	background: #242424;
	height: 100%;
	padding: 5px;
	display: inline-block;
	line-height: 38px;
	text-align: center;
	border: #fddebf 1px solid;
	-moz-border-radius: 10px;
	-webkit-border-radius: 10px;
	border-radius: 10px;
	margin: 5px;
	cursor: pointer;
  }
  
  .action-button:hover {
    background: rgba(255, 255, 255, 0.1);
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  }
  
  .action-button i {
    font-size: 20px;
  }
  
  /* 弹窗样式 */
  .offering-dialog {
    :deep(.el-dialog) {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(10px);
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
    }
  
    .offering-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
      gap: 20px;
      padding: 20px;
    }
  }
  
  .offering-option {
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 15px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s;
    background: white;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  
    &:hover {
      transform: scale(1.05) translateY(-5px);
      box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
    }
  
    img {
      width: 80px;
      height: 80px;
      object-fit: contain;
      margin-bottom: 10px;
    }
  
    .offering-info {
      .name {
        font-size: 16px;
        color: #333;
        margin-bottom: 5px;
      }
      
      .price {
        font-size: 14px;
        color: #666;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5px;
        
        &::before {
          content: '';
          width: 16px;
          height: 16px;
          background: url('/assets/coin.png') no-repeat center;
          background-size: contain;
        }
      }
    }
  }

  /* 祭品区域 */
  .offerings-area {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
	z-index: 100;
  }
  
  .offering-table {
    position: absolute;
    bottom: 100px;
    left: 50%;
    transform: translateX(-50%);
    width: 300px;
    height: 100px;
  }
  
  .table-surface {
    width: 100%;
    height: 20px;
    background: linear-gradient(to bottom, #d4d4d4, #a0a0a0);
    border-radius: 5px;
  }
  
  .incense-holder {
    position: absolute;
    top: -30px;
    left: 50%;
    transform: translateX(-50%);
    width: 40px;
    height: 40px;
    background: #8b4513;
    border-radius: 50%;
  }
  
  .incense-ash {
    position: absolute;
    top: 5px;
    left: 50%;
    transform: translateX(-50%);
    width: 20px;
    height: 20px;
    background: #dcdcdc;
    border-radius: 50%;
  }
  
  .offering-item {
    position: absolute; /* Positioned relative to memorial-area */
    cursor: move;
    user-select: none;
    /* 将transition从这里移除，避免拖动过程中的动画干扰 */
    filter: drop-shadow(0 0.3125rem 0.3125rem rgba(0, 0, 0, 0.3)); /* 5px 5px */
    pointer-events: all; /* Enable interaction */
    z-index: 1; /* 默认z-index */
    will-change: transform; /* 提示浏览器元素将被频繁改变，可提高性能 */
  }
  .offering-item span{
	color: #f00;
	/* font-weight: bold; */
	font-size: 22px;
	text-wrap: wrap;
  }
  /* 分离悬停和拖动状态的样式处理 */
  .offering-item:hover:not(.dragging) {
    transform: scale(1.1) translateY(-0.3125rem); /* 5px */
    filter: drop-shadow(0 0.625rem 0.625rem rgba(0, 0, 0, 0.4)); /* 10px 10px */
    transition: transform 0.3s, filter 0.3s; /* 只在悬停时应用过渡 */
  }
  
  /* 单独设置拖动中的样式 */
  .offering-item.dragging {
    transform: scale(1.1); /* 只缩放，不上移，避免退缩感 */
    filter: drop-shadow(0 0.625rem 0.625rem rgba(0, 0, 0, 0.5)); /* 更明显的阴影 */
    /* 拖动时不应用过渡效果 */
    opacity: 0.9; /* 轻微透明提示正在拖动 */
  }
  
  .offering-item img {
    /* width: 3.75rem; 60px */
    /* height: 3.75rem; 60px */
	width: auto;
	height: auto;
    object-fit: contain;
    display: block; /* Prevents bottom space */
    pointer-events: none; /* 防止图片接收事件，确保事件传递给父元素 */
	border: 1px solid #f00;
  }


  .placed-item-display {
   position: absolute; /* 确保使用 style 中的 left/top 定位 */
   /* 添加一些基本样式 */
   img {
     /* max-width: 80px; */
     /* max-height: 80px; */
     object-fit: contain;
   }
}


/* ===== 添加的部分 开始 ===== */
.hover-info-overlay-simple {
  position: absolute; /* 关键：相对于已绝对定位的 .placed-item-display 定位 */
  top: 100%;
  left: 0;
  width: 200px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 6px 10px;
  box-sizing: border-box;
  line-height: 1.4;
  text-align: left;
  pointer-events: none;
}

.hover-info-text-simple {
  margin: 0 0 3px 0;
  font-size: 0.8rem;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.hover-info-time-simple {
  margin: 0;
  font-size: 0.7rem;
  opacity: 0.85;
}

/* 过渡动画 */
.info-overlay-fade-enter-active,
.info-overlay-fade-leave-active {
  transition: opacity 0.25s ease;
}

.info-overlay-fade-enter-from,
.info-overlay-fade-leave-to {
  opacity: 0;
}
/* ===== 添加的部分 结束 ===== */

.tombstone-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 25px; /* 增大间距 */
}

.graveyard_audio{
	position: fixed;
	top: 140px;
	right: 20px;
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
	width: 60px;
	height: 60px;
	padding: 10px;
	box-sizing: border-box;
	cursor: pointer;
	background-color: rgba(0, 0, 0, 0.5);
	border-radius: 50%;

	/* 关键：设置旋转动画 */
	animation-name: spin;
	animation-duration: 5s; /* 旋转一周所需的时间 */
	animation-iteration-count: infinite; /* 无限次重复 */
	animation-timing-function: linear; /* 匀速旋转 */
	animation-play-state: paused; /* 默认暂停 */
}
.graveyard_audio img{
	width: 100%;
	height: 100%;
	object-fit: contain;
}
.playing{
	animation-play-state: running;
}

/* 定义旋转动画关键帧 */
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.graveyard_fullScreen{
	position: fixed;
	top: 60px;
	right: 20px;
	width: 60px;
	height: 60px;
	padding: 10px;
	z-index: 3004;

	display: flex;
	align-items: center;
	justify-content: center;
	box-sizing: border-box;
	cursor: pointer;
	background-color: rgba(0, 0, 0, 0.5);
	border-radius: 50%;
}
.graveyard_fullScreen image{
	width: 100%;
	height: 100%;
	object-fit: contain;
}
.graveyard_QRcode{
	position: fixed;
	top: 240px;
	right: 20px;
	width: 60px;
	height: 60px;
	padding: 10px;
	z-index: 3004;
	display: flex;
	align-items: center;
	justify-content: center;
	box-sizing: border-box;
	cursor: pointer;
	background-color: rgba(255, 255, 255, 1);
	border-radius: 50%;
}
.graveyard_QRcode image{
	width: 100%;
	height: 100%;
	object-fit: contain;
}
.placed-item:hover{
	border: 1px #fc0 dotted;
}


.top_bg{
	width: 100%;
    left: 0;
    margin: 0 auto;
    height: 42px;
    background: #000;
    position: fixed;
    top: 0;
    z-index: 304;
    background-color: rgba(0, 0, 0, 0.6);
    overflow: hidden;

	/* === 核心：定义过渡效果 === */
	/* 对 max-height 属性进行过渡 */
	/* 持续时间 2s */
	transition: height 1s ease;
}
.top_bg.is-expanded{
	height: 160px;
}
.TopMin320{
	width: 100%;
    min-width: 600px;
    margin: 0 auto;
    position: relative;
    line-height: 40px;
    text-align: center;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.top_logo{
	padding-left: 8px;
    font-size: 1.4rem;
	color: #e0caba;
    font-family: cursive;
}
.top_left{
	margin-left: 15px;
    color: #e0caba;
    width: auto;
    max-width: 30%;
    overflow: hidden;
    z-index: 99998;
	display: flex;
	flex-flow: column;
	align-items: flex-start;
	height: 100%;
}
.top_left .jngname{
	line-height: 40px;
    font-size: 1.3rem;
	display: flex;
	align-items: center;
	justify-content: flex-start;
}
.caret {
    display: inline-block;
    width: 0;
    height: 0;
    margin-left: 2px;
    vertical-align: middle;
    border-top: 4px dashed;
    border-top: 4px solid\9;
    border-right: 4px solid transparent;
    border-left: 4px solid transparent;
}

.centerdiv {
    position: absolute;
    top: 0;
    left: 35%;
    width: 40%;
    height: 38px;
    line-height: 38px;
    margin: 0 auto;
    text-align: center;
    overflow: hidden;
    color: #e0caba;
}

.centerdiv>Marquee {
    margin: 0;
    height: 38px;
    overflow: hidden;
    font-size: 1.2rem;
}
.top_right {
    /* float: right; */
    padding: 0;
    margin: auto;
    margin-right: 50px;
    font-size: 1rem;
    z-index: 99998;
    height: 40px;
	display: flex;
	align-items: center;
}
.top_right div button {
	width: 75px;
	height: 28px;
    font-size: 1rem;
    overflow: hidden;
    font-family: Arial, '微软雅黑';
	display: flex;
	align-items: center;
	justify-content: center;
	color: #ffffff;
	border-radius: 6px;
}

.jnginfo {
    position: relative;
    width: 100%;
    padding-left: 200px;
    z-index: 99996;
    color: #e0e0e0;
    text-align: left;
    height: 100px;
}

/* .jnginfo.show {
    opacity: 1;
    transform: translateY(0);
    height: auto;
    padding: 10px;
    padding-left: 120px;
} */
.jnginfo p {
    line-height: 200%;
    font-size: 1.1rem;
}

.qrcode-view{
    width: 100%;
    display: flex;
    flex-flow: column;
    align-items: center;
    gap: 20px 0;
}


</style>
